package com.example.mybatisplus.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.mybatisplus.common.JsonResponse;
import com.example.mybatisplus.mapper.StudentMapper;
import ch.qos.logback.classic.net.server.HardenedLoggingEventInputStream;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.mybatisplus.model.domain.*;
import com.example.mybatisplus.model.domain.Class;
import com.example.mybatisplus.model.domain.*;
import com.example.mybatisplus.model.dto.AdjustForm;
import com.example.mybatisplus.model.dto.HygieneForm;
import com.example.mybatisplus.model.dto.IndisciplineForm;
import com.example.mybatisplus.model.dto.RepairForm;
import com.example.mybatisplus.service.*;
import org.apache.ibatis.annotations.Update;
import org.springframework.boot.SpringApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.example.mybatisplus.common.JsonResponse;
import com.example.mybatisplus.model.dto.RoomAdjustForm;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


/**
 *
 *  前端控制器
 *
 *
 * @author zzy
 * @since 2024-06-24
 * @version v1.0
 */
@RestController
@RequestMapping("/api/leader")
public class LeaderController {

    private final Logger logger = LoggerFactory.getLogger( LeaderController.class );

    @Autowired
    private LeaderService leaderService;
    @Autowired
    private CollegeService collegeService;
    @Autowired
    private MajorService majorService;
    @Autowired
    private ClassService classService;
    @Autowired
    private AreaService areaService;
    @Autowired
    private BuildingService buildingService;
    @Autowired
    private RoomService roomService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private AdjustDormitoryService adjustDormitoryService;
    @Autowired
    private HygieneCheckService hygieneCheckService;
    @Autowired
    private IndisciplineService indisciplineService;
    @Autowired
    private RepairService repairService;
    @Autowired
    private StudentMapper studentMapper;
    /**
    * 描述：根据Id 查询
    *
    */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getById(@PathVariable("id") Long id)throws Exception {
        Leader  leader =  leaderService.getById(id);
        return JsonResponse.success(leader);
    }

    /**
    * 描述：根据Id删除
    *
    */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public JsonResponse deleteById(@PathVariable("id") Long id) throws Exception {
        leaderService.removeById(id);
        return JsonResponse.success(null);
    }


    /**
    * 描述：根据Id 更新
    *
    */
    @RequestMapping(value = "", method = RequestMethod.PUT)
    @ResponseBody
    public JsonResponse updateLeader(Leader  leader) throws Exception {
        leaderService.updateById(leader);
        return JsonResponse.success(null);
    }


    /**
    * 描述:创建Leader
    *
    */
    @RequestMapping(value = "", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse create(Leader  leader) throws Exception {
        leaderService.save(leader);
        return JsonResponse.success(null);
    }
    @GetMapping("/loadColleges")
    @ResponseBody
    public JsonResponse loadColledges() {
        List<College> list1 = collegeService.list();
        List<Map<String, Object>> mapList = new ArrayList<>();
        list1.forEach(
                college -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("ID", college.getId());
                    map.put("colledgeName", college.getName());
                    mapList.add(map);
                }
        );
        return JsonResponse.success(list1);
    }

    @GetMapping("/loadMajors")
    @ResponseBody
    public JsonResponse loadMajors(Long CollegeID) {

        List<Major> list1 = majorService.selectMajorByCollegeId(CollegeID);
        List<Map<String, Object>> mapList = new ArrayList<>();
        list1.forEach(
                college -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("ID", college.getId());
                    map.put("majorName", college.getName());
                    mapList.add(map);
                }
        );
        return JsonResponse.success(list1);
    }

    @GetMapping("/loadClasses")
    @ResponseBody
    public JsonResponse loadClasses(Long MajorID) {
        List<Class> list1 = classService.selectClassByMajorID(MajorID);
        List<Map<String, Object>> mapList = new ArrayList<>();
        list1.forEach(
                college -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("ID", college.getId());
                    map.put("className", college.getName());
                    mapList.add(map);
                }
        );
        return JsonResponse.success(list1);
    }

    @GetMapping("/loadAreas")
    @ResponseBody
    public JsonResponse loadAreas() {
        List<Area> list1 = areaService.list();
        List<Map<String, Object>> mapList = new ArrayList<>();
        list1.forEach(
                college -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("ID", college.getId());
                    map.put("areaName", college.getName());
                    mapList.add(map);
                }
        );
        return JsonResponse.success(list1);
    }

    @GetMapping("/loadBuildings")
    @ResponseBody
    public JsonResponse loadBuildings(Long AreaID) {
        List<Building> list1 = buildingService.selectBuildingByAreaID(AreaID);
        List<Map<String, Object>> mapList = new ArrayList<>();
        list1.forEach(
                college -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("ID", college.getId());
                    map.put("buildingName", college.getName());
                    mapList.add(map);
                }
        );
        return JsonResponse.success(list1);
    }

    @GetMapping("/loadRooms")
    @ResponseBody
    public JsonResponse loadRooms(Long BuildingID) {
        List<Room> list1 = roomService.selectRoomByBuildingID(BuildingID);
        List<Map<String, Object>> mapList = new ArrayList<>();
        list1.forEach(
                college -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("ID", college.getId());
                    map.put("roomName", college.getName());
                    mapList.add(map);
                }
        );

        return JsonResponse.success(list1);
    }


//    @GetMapping("/handleSelectCollege")
//    @ResponseBody
//    public JsonResponse handleSelectCollege(Long collegeID) {
//        List<Student> list1 = studentService.selectStudentByCollegeId(collegeID);
//        return JsonResponse.success(list1);
//    }


    @PostMapping("/selectByCollege")
    @ResponseBody
    public JsonResponse selectStudentByCollegeName(@RequestBody Dot dot) {
        dot.setPageNo((dot.getPageNo()-1)*dot.getPageSize());
        List<Student> list = studentService.selectStudentByCollegeName(dot);
        return JsonResponse.success(list);
    }

    @PostMapping("/selectByMajor")
    @ResponseBody
    public JsonResponse selectByMajor(@RequestBody Dot dot) {
        dot.setPageNo((dot.getPageNo()-1)*dot.getPageSize());
        List<Student> list = studentService.selectStudentByCollegeName(dot);
        return JsonResponse.success(list);
    }

    @PostMapping("/selectByClass")
    @ResponseBody
    public JsonResponse selectByClass(@RequestBody Dot dot) {
        dot.setPageNo((dot.getPageNo()-1)*dot.getPageSize());
        List<Student> list = studentService.selectStudentByCollegeName(dot);
        return JsonResponse.success(list);
    }

    @PostMapping("/searchStudentByCollegeIDMajorIDClassID")
    @ResponseBody
    public JsonResponse handleSelectClass(@RequestBody Dot dot) {
        dot.setPageNo((dot.getPageNo()-1)*dot.getPageSize());
        List<Student> list1 = studentService.selectStudentByCollegeIdAndMajorIdAndClassId(dot);
        return JsonResponse.success(list1);
    }
    @GetMapping("/handleSelectStudentByBuildingAndArea")
    @ResponseBody
    public JsonResponse handSelectBuilding(Long areaID, Long buildingID) {
        List<Student> list1 = studentService.handSelectStudentByBuilding(areaID, buildingID, null);
        return JsonResponse.success(list1);
    }
    @GetMapping("/handleSelectStudentByBuildingAndAreaAndRoom")
    @ResponseBody
    public JsonResponse handSelectBuilding(Long areaID, Long buildingID, Long roomID) {
        List<Student> list1 = studentService.handSelectStudentByBuilding(areaID, buildingID, roomID);
        return JsonResponse.success(list1);
    }

    public static List<Integer> convertObjectToList(Object object) {
        if (object instanceof Collection) {
            // 转换为Collection
            Collection<?> collection = (Collection<?>) object;
            // 转换Collection中的每个元素为Integer，并收集到新的列表中
            return collection.stream()
                    .mapToInt(e -> (Integer) e)
                    .boxed()
                    .collect(Collectors.toList());
        } else {
            throw new IllegalArgumentException("The Object is not a Collection");
        }
    }

    @PostMapping("/searchStudentByAll")
    @ResponseBody
    public JsonResponse searchStudentByAll(@RequestBody Dot dot){
        dot.setPageNo((dot.getPageNo()-1)*dot.getPageSize());
        List<Student> students = studentService.selectStudentByAll(dot);
        return JsonResponse.success(students);
    }

    @PostMapping("/batchAllocationWithBirthplace")
    @ResponseBody
    public JsonResponse batchAllocationWithBirthplace(@RequestBody Map<String, Object> names) {
        String s = studentService.batchAllocationWithBirthplace(names);
        if(s.equals("Allocate success"))return JsonResponse.success(s);
        return JsonResponse.failure(s);
    }
    @PostMapping("/getAllAdjustApplication")
    @ResponseBody
    public JsonResponse getAllAdjustApplication(@RequestBody Dot dot) {
        dot.getData().put("ID", Long.parseLong((String) dot.getData().get("ID")));
        List<RoomAdjustForm> RoomAdjustForms = leaderService.getAllAdjustApplication(dot);
        int start = (dot.getPageNo()-1)*dot.getPageSize();
        int end = start+dot.getPageSize();
        Map<String, Object> map = new HashMap<>();
        map.put("totalNum", RoomAdjustForms.size());
        RoomAdjustForms = RoomAdjustForms.subList(start, Math.min(end, RoomAdjustForms.size()));
        return JsonResponse.success(RoomAdjustForms, "success").setOtherData(map);
    }
    @PostMapping("/getBuildingsByGender")
    @ResponseBody
    public JsonResponse getBuildingsByGender(@RequestBody Map<String, String> params) {
        Long ID = Long.parseLong(params.get("ID"));
        List<Building> buildings = leaderService.getBuildingsByGender(ID);
        return JsonResponse.success(buildings);
    }
    @PostMapping("/updateAdjustByLeader")
    @ResponseBody
    public JsonResponse updateAdjustByLeader(@RequestBody Map<String, String> params) {
        Long ID = Long.parseLong(params.get("ID"));
        Long buildingID = Long.parseLong(params.get("buildingID"));
        if(leaderService.updateAdjustByLeader(ID, buildingID)){
            return JsonResponse.success(true);
        }else{
            return JsonResponse.failure("修改失败");
        }
    }
    @PostMapping("/approveAdjustByLeader")
    @ResponseBody
    public JsonResponse approveAdjustByLeader(@RequestBody Map<String, String> params) {
        Long ID = Long.parseLong(params.get("ID"));
        Long leaderID = Long.parseLong(params.get("leaderID"));
        String state = params.get("state");
        if(leaderService.approveAdjustByLeader(ID, leaderID, state)){
            return JsonResponse.success(true);
        }else{
            return JsonResponse.failure("修改失败");
        }
    }
    @PostMapping("/getCheckOutApplication")
    @ResponseBody
    public JsonResponse getCheckOutApplication(@RequestBody Dot dot) {
        dot.getData().put("ID", Long.parseLong((String) dot.getData().get("ID")));
        List<RoomAdjustForm> RoomAdjustForms = leaderService.getCheckOutApplication(dot);
        int start = (dot.getPageNo()-1)*dot.getPageSize();
        int end = start+dot.getPageSize();
        Map<String, Object> map = new HashMap<>();
        map.put("totalNum", RoomAdjustForms.size());
        RoomAdjustForms = RoomAdjustForms.subList(start, Math.min(end, RoomAdjustForms.size()));
        return JsonResponse.success(RoomAdjustForms, "success").setOtherData(map);
    }
    @PostMapping("/UpdateCheckOutApplication")
    @ResponseBody
    public JsonResponse UpdateCheckOutApplication(@RequestBody Map<String, String> params) {
        Long ID = Long.parseLong(params.get("ID"));
        Long leaderID = Long.parseLong(params.get("leaderID"));
        if(leaderService.UpdateCheckOutApplication(ID, leaderID)){
            return JsonResponse.success(true);
        }else{
            return JsonResponse.failure("修改失败");
        }
    }
    @PostMapping("/getIndisciplineAudit")
    @ResponseBody
    public JsonResponse getIndisciplineAudit(@RequestBody Dot dot) {
        dot.getData().put("ID", Long.parseLong((String) dot.getData().get("ID")));
        List<Indiscipline> indisciplines = leaderService.getIndisciplineAudit(dot);
        int start = (dot.getPageNo()-1)*dot.getPageSize();
        int end = start+dot.getPageSize();
        Map<String, Object> map = new HashMap<>();
        map.put("totalNum", indisciplines.size());
        indisciplines = indisciplines.subList(start, Math.min(end, indisciplines.size()));
        return JsonResponse.success(indisciplines, "success").setOtherData(map);
    }
    @PostMapping("/updateIndisciplineAudit")
    @ResponseBody
    public JsonResponse updateIndisciplineAudit(@RequestBody Map<String, String> params) {
        Long ID = Long.parseLong(params.get("ID"));
        Long leaderID = Long.parseLong(params.get("leaderID"));
        int score = Integer.parseInt(params.get("score"));
        if(leaderService.updateIndisciplineAudit(ID, leaderID, score)){
            return JsonResponse.success(true);
        }else{
            return JsonResponse.failure("修改失败");
        }
    }

    @PostMapping("/batchAllocationWithNation")
    @ResponseBody
    public JsonResponse batchAllocationWithNation(@RequestBody Map<String, Object> names) {

        String s = studentService.batchAllocationWithNation(names);
        if(s.equals("Allocate success"))return JsonResponse.success(s);
        return JsonResponse.failure(s);
    }
    @PostMapping("/batchCheckout")
    public JsonResponse batchCheckout(@RequestBody Map<String, Object> students){
        List<Student> students1 = null;
        try {
            students1 = studentService.convertObjectToListStudent(students.get("students"));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        Long leaderID = Long.parseLong(students.get("LeaderID").toString());
        List<AdjustDormitory> list = new ArrayList<>();
        for(int i=0;i<students1.size();i++){
            list.add(new AdjustDormitory()
                    .setModifiedTime(LocalDateTime.now())
                    .setCreatedTime(LocalDateTime.now())
                    .setStudent(students1.get(i).getId())
                    .setOutRoom(students1.get(i).getRoom())
                    .setState("已完成")
                    .setLeader(leaderID)
            );
            students1.get(i).setRoom(null);
            UpdateWrapper<Student> wrapper = new UpdateWrapper<>();
            wrapper.eq("ID", students1.get(i).getId()).set("room", null).set("modified_time",LocalDateTime.now());
            studentMapper.update(null,wrapper);


        }


        boolean b2 = adjustDormitoryService.saveBatch(list);
        if(b2)return JsonResponse.success(true);
        else return JsonResponse.failure("Fail to check out.");
    }

    @PostMapping("/batchExchange")
    public JsonResponse batchExchange(@RequestBody Map<String,Object> params){
        String s = studentService.batchExchange(params);
        return JsonResponse.success(s);
    }
    @PostMapping("/selectAllocationAdjust")
    public JsonResponse selectAllocationAdjust(@RequestBody Dot dot){
        dot.setPageNo((dot.getPageNo()-1)*dot.getPageSize());
        List<AdjustForm> adjustForms = adjustDormitoryService.selectAllocationAdjust(dot);
        return JsonResponse.success(adjustForms);
    }
    @PostMapping("/getHygiene")
    public JsonResponse getHygiene(@RequestBody Dot dot){
        dot.setPageNo((dot.getPageNo()-1)*dot.getPageSize());
        List<HygieneForm> list = hygieneCheckService.getHygiene(dot);
        return JsonResponse.success(list);
    }
    @PostMapping("/getIndiscipline")
    public JsonResponse getIndiscipline(@RequestBody Dot dot){
        dot.setPageNo((dot.getPageNo()-1)*dot.getPageSize());
        List<IndisciplineForm> list = indisciplineService.getIndiscipline(dot);
        return JsonResponse.success(list);
    }

    @PostMapping("/getRepair")
    public JsonResponse getRepair(@RequestBody Dot dot){
        dot.setPageNo((dot.getPageNo()-1)*dot.getPageSize());
        List<RepairForm> list = repairService.getRepair(dot);
        return JsonResponse.success(list);
    }

}

